package com.book.common.utils;

import com.book.book.NovelSiteEnum;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/***
 * @Author Lin
 * @Date Create By 16:31 2017/10/4
 * @Description
 */
public final class NovelSpiderUtil {
    private static final Map<NovelSiteEnum, Map<String, String>> contextMap = new HashMap<>();

    private NovelSpiderUtil() {
    }

    static {
        init();
    }

    private static void init() {
        SAXReader reader = new SAXReader();
        try {
            URL url = NovelSpiderUtil.class.getClassLoader().getResource("com/book/common/utils/spider-rule.xml");
            String filepath = url.getPath();
            //System.out.println(filepath);
            Document doc = reader.read(new File(filepath));
            Element root = doc.getRootElement();
            List<Element> sites = root.elements("site");
            for (Element site : sites) {
                List<Element> subs = site.elements();
                HashMap<String, String> subMap = new HashMap<>();
                for (Element sub : subs) {
                    String name = sub.getName();
                    String text = sub.getTextTrim();
                    subMap.put(name, text);
                }
                contextMap.put(NovelSiteEnum.getEnumByUrl(subMap.get("url")), subMap);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param novelSiteEnum
     * @Author: Lin
     * @Description: 拿到对应网站的解析规则
     * @Date: 17:21 2017/10/4
     */
    public static Map<String, String> getContext(NovelSiteEnum novelSiteEnum) {
        return contextMap.get(novelSiteEnum);

    }

    /**
     * 多个文件合并为一个文件，合并规则：按文件名分割排序
     *
     * @param path        基础目录，该根目录下的所有文件都会被合并到mergeToFile
     * @param mergeToFile 被合并的文本文件，这个参数可以null，合并后的文件保存在path/merge.txt
     */
    public static void multiFileMerge(String path, String mergeToFile, boolean deleteThisFile) {
        mergeToFile = mergeToFile == null ? path + "/merge.txt" : mergeToFile;
        File[] files = new File(path).listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".txt");
            }
        });
        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                int o1Index = Integer.parseInt(o1.getName().split("\\-")[0]);
                int o2Index = Integer.parseInt(o2.getName().split("\\-")[0]);
                if (o1Index > o2Index)
                    return 1;
                else if (o1Index == o2Index)
                    return 0;
                else return -1;
            }
        });
        PrintWriter out = null;
        try {
            out = new PrintWriter(new File(mergeToFile), "UTF-8");
            for (File file : files) {
                BufferedReader bufr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
                String line = null;
                while ((line = bufr.readLine()) != null) {
                    out.println(line);
                }
                bufr.close();
                if (deleteThisFile) {
                    file.delete();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            out.close();
        }
    }

    /**
     * 获取书籍的状态
     *
     * @param status
     * @return
     */
    public static int getNovelStatus(String status) {
        if (status.contains("连") || status.contains("更")) {
            return 1;
        } else if (status.contains("完")) {
            return 2;
        } else {
            throw new RuntimeException("不支持的书籍状态" + status);
        }
    }

    /**
     * 格式化日期字符串为日期对象
     *
     * @param dateStr
     * @param pattern
     * @return
     * @throws ParseException
     */
    public static Date getDate(String dateStr, String pattern) throws ParseException {
        if ("MM-dd".equals(pattern)) {
            pattern = "yyyy-MM-dd";
            dateStr = getDateField(Calendar.YEAR) + "-" + dateStr;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date date = sdf.parse(dateStr);
        return date;
    }

    public static String getDateField(int field) {
        Calendar cal = new GregorianCalendar();
        return cal.get(field) + "";
    }
}
